<template>
  <view class="container">
    <scroll-view
      class="content"
      :class="activeTab"
      scroll-y
      @scrolltolower="onScrollToLower"
      @scroll="handleScroll"
    >
      <view class="header" :style="{ backgroundColor: currentTabType.bgColor }">
        <swiper
          class="banner"
          circular
          autoplay
          interval="3000"
          duration="500"
          indicator-color="rgba(255, 255, 255, 0.6)"
          indicator-active-color="#ffffff"
        >
          <swiper-item v-for="(item, index) in bannerImages" :key="index">
            <image class="banner-image" :src="item" mode="aspectFill" />
          </swiper-item>
        </swiper>
      </view>
      <view class="sticky-tabs" :class="{ 'sticky-bg': isTabSticky }">
        <view class="tabs">
          <view
            v-for="type in Object.values(TAB_TYPES)"
            :key="type.key"
            class="tab"
            :class="{ active: activeTab === type.key }"
            :style="{ color: type.color }"
            @click="setActiveTab(type.key)"
          >
            {{ type.label }}
          </view>
          <view class="filter-btn" @click="handleFilterClick">
            <uni-icons type="settings" size="20" color="#4CAF50" />
            <!-- <text>筛选</text> -->
          </view>
          <filter-panel
            ref="filterPanel"
            :location-filters="locationFilters"
            @confirm="handleFilterConfirm"
          />
        </view>
      </view>
      <view class="list">
        <view class="list">
          <view
            class="list-item"
            v-for="(item, index) in filteredListFromFilterPanel.length == 0
              ? filteredList
              : filteredListFromFilterPanel"
            :key="item.id"
          >
            <view v-if="item.article_info">
              <image
                class="item-image"
                :src="item.article_info.image"
                mode="aspectFill"
                @click="
                  () => {
                    handleItemClick(item.article_info);
                  }
                "
              />
            </view>
            <CouponItem
              v-if="item.coupon_info"
              :coupon-data="getCouponData(item.coupon_info)"
            />
          </view>

          <view v-if="isLoading" class="loading">
            <text>加载中...</text>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>
<script>
import { store as appStore, mutations } from "@/store/index.js";
import { store as uniIdPagesStore } from "@/uni_modules/uni-id-pages/common/store.js";
import CouponItem from "@/components/coupon-item/coupon-item.vue";
import FilterPanel from "@/components/filter-panel/filter-panel.vue";

export default {
  components: {
    CouponItem,
    FilterPanel,
  },
  data() {
    return {
      filteredListFromFilterPanel: [], // 筛选面板筛选后的文章数据
      originalArticles: [], // 用于保存原始文章数据
      timeFilters: undefined,
      currentTimeFilter: "all",
      currentLocationFilter: "all",
      isTabSticky: false,
      currentCategoryId: "",
      isLoading: false,
      TAB_TYPES: {
        BASIC: {
          key: "basic",
          label: "基础类型",
          color: "#4caf50",
          bgColor: "rgba(76, 175, 80, 0.08)",
          category_id: "",
        },
        PREMIUM: {
          key: "premium",
          label: "提升类型",
          color: "#daa520",
          bgColor: "rgba(218, 165, 32, 0.08)",
          category_id: "",
        },
      },
      bannerLoading: false,
      activeTab: "basic",
    };
  },
  computed: {
    redirectUrl() {
      return appStore.redirectUrl || "";
    },
    hasLogin() {
      return uniIdPagesStore.hasLogin;
    },
    bannerImages() {
      return appStore.bannerImages || [];
    },
    listTotalCount() {
      return appStore.listTotalCount || 0;
    },
    categories() {
      this.initializeCategories();
      return !appStore.categories ||
        !Array.isArray(appStore.categories) ||
        appStore.categories.length === 0
        ? []
        : appStore.categories;
    },
    locationFilters() {
      return this.convertArticlesToLocationFilters(appStore.articles);
    },
    filteredList() {
      const result = this.convertArticlesToData(appStore.articles).filter(
        (item) => item.article_info.type === this.activeTab
      );
      // console.log("filteredList result: ", result);
      // console.log("appStore.articles: ", appStore.articles);
      return result;
    },
    currentTabType() {
      return this.getTabTypeByKey(this.activeTab);
    },
    contentStyle() {
      return {
        backgroundColor: this.currentTabType.bgColor,
      };
    },
  },
  methods: {
    convertArticlesToLocationFilters(articles) {
      const regionSet = new Set();
      const result = [];

      // 添加默认选项
      result.push({ label: "全部", value: "all" });

      articles.forEach((article) => {
        const regionAddress = article.region_address;
        if (regionAddress && regionAddress.text && regionAddress.value) {
          const length = Math.min(
            regionAddress.text.length,
            regionAddress.value.length
          );
          for (let i = 0; i < length; i++) {
            const key = `${regionAddress.text[i]}_${regionAddress.value[i]}`;
            if (!regionSet.has(key)) {
              regionSet.add(key);
              result.push({
                label: regionAddress.text[i],
                value: regionAddress.value[i],
              });
            }
          }
        }
      });

      return result;
    },
    handleFilterClick() {
      this.$refs.filterPanel.openFilter();
    },
    handleFilterConfirm({ timeFilter, locationFilter }) {
      this.currentTimeFilter = timeFilter;
      this.currentLocationFilter = locationFilter;
      this.applyFilters();
    },
    applyFilters() {
      // 获取所有原始文章数据
      const allOriginalArticles = this.convertArticlesToData(appStore.articles);

      // 筛选文章数据
      const filteredArticles = allOriginalArticles.filter((item) => {
        // 类型筛选
        const typeMatch = item.article_info.type === this.activeTab;

        // 地点筛选
        const locationMatch =
          this.currentLocationFilter === "all" ||
          item.article_info.region_address?.value?.includes(
            this.currentLocationFilter
          );

        // 时间筛选
        const timeMatch = this.$refs.filterPanel.isTimeInRange(
          item.article_info.start_time
        );

        return typeMatch && locationMatch && timeMatch;
      });

      // 更新显示的文章列表
      this.filteredListFromFilterPanel = filteredArticles;

      // console.log("筛选结果:", {
      //   currentTimeFilter: this.currentTimeFilter,
      //   currentLocationFilter: this.currentLocationFilter,
      //   filteredCount: this.filteredListFromFilterPanel.length,
      //   totalCount: allOriginalArticles.length,
      // });
    },

    /**
     * 根据筛选条件过滤文章数据
     * @param {Array} articles - 文章数据数组
     * @param {string} timeRange - 时间范围(week/month/year/all)
     * @param {string} locationCode - 地区编码
     * @returns {Array} 过滤后的文章数据
     */
    filterArticles(articles, timeRange, locationCode) {
      const currentDate = new Date();
      let startDate = new Date();

      // 计算时间范围
      switch (timeRange) {
        case "week":
          startDate.setDate(currentDate.getDate() - 7);
          break;
        case "month":
          startDate.setMonth(currentDate.getMonth() - 1);
          break;
        case "year":
          startDate.setFullYear(currentDate.getFullYear() - 1);
          break;
        default:
          startDate = null;
      }

      return articles.filter((article) => {
        // 时间筛选
        const timeMatch =
          !startDate || new Date(article.article_info.date) >= startDate;

        // 地点筛选
        const locationMatch =
          locationCode === "all" ||
          article.article_info.region_address?.value?.includes(locationCode);

        return timeMatch && locationMatch;
      });
    },
    handleScroll(e) {
      this.isTabSticky = e.detail.scrollTop > 200;
    },
    getCouponData(item) {
      const couponInfo = item;
      return {
        name: couponInfo.name || "优惠券",
        discount: couponInfo.discount || 0,
        validity: couponInfo.validity || "暂无日期",
        customImage: couponInfo.customImage || "",
        _id: couponInfo._id,
      };
    },
    setRedirectUrlData(item) {
      const url = `/pages/list/detail?id=${encodeURIComponent(
        item.id
      )}&content=${encodeURIComponent(item.content)}&title=${encodeURIComponent(
        item.title
      )}`;
      appStore.redirectUrl = url;
    },
    handleItemClick(item) {
      // console.log("handleItemClick item: ", item);
      this.setRedirectUrlData(item);

      uni.navigateTo({
        url: this.redirectUrl,
        fail: (err) => {
          console.error("页面跳转失败：", err);
          uni.showToast({
            title: "页面跳转失败",
            icon: "none",
          });
        },
      });
    },

    /**
     * 设定种类的内容
     */
    initializeCategories() {
      if (
        !appStore.categories ||
        !Array.isArray(appStore.categories) ||
        appStore.categories.length === 0
      )
        return;

      const listTabs = appStore.categories;

      for (let index = 0; index < listTabs.length; index++) {
        const element = listTabs[index];
        const types = Object.values(this.TAB_TYPES);

        types[index].label = element.label;
        types[index].category_id = element.category_id;
      }

      this.currentCategoryId = listTabs[0].category_id; // 默认选择第一个 tab
    },
    async onScrollToLower() {
      if (this.isLoading) return;

      // 检查是否已加载全部数据
      if (
        appStore.articles.length >= this.listTotalCount &&
        this.listTotalCount > 0
      ) {
        return;
      }

      this.isLoading = true;
      try {
        await mutations.loadMore(this.currentCategoryId);
      } catch (e) {
        console.error(e);
      } finally {
        this.isLoading = false;
      }
    },
    /**
     * 将articles的数据转化为listData
     */
    convertArticlesToData(articles) {
      // 检查 articles 是否为空或未定义
      if (!articles || !Array.isArray(articles) || articles.length === 0)
        return [];

      // console.log("articles: ", articles);

      const result = articles.map((item) => {
        // 判断是否包含优惠券信息
        const hasCoupon =
          item.coupon_info && Object.keys(item.coupon_info).length > 0;
        let res = {};

        // 基础文章数据
        const article_info = {
          id: item._id,
          title: item.title,
          date: item.publish_date,
          type:
            item.type === 0
              ? this.TAB_TYPES.BASIC.key
              : this.TAB_TYPES.PREMIUM.key,
          image: item.avatar,
          content: item.content,
          region_address: item.region_address,
          start_time: item.start_time,
          // itemType: hasCoupon ? 'coupon' : 'article'
        };

        res = {
          article_info,
        };

        // 如果有优惠券信息，合并优惠券数据
        if (hasCoupon) {
          const coupon_info = {
            ...item.coupon_info[0],
          };

          res.coupon_info = coupon_info;
        }

        return res;
      });

      return result;
    },
    async setActiveTab(tab) {
      if (tab === this.activeTab) return;

      this.activeTab = tab;
      this.currentCategoryId = this.getTabTypeByKey(tab).category_id;

      await mutations.loadArticles(this.currentCategoryId);
      // 保存原始数据
      this.originalArticles = [...appStore.articles];
    },
    getTabTypeByKey(key) {
      return (
        Object.values(this.TAB_TYPES).find((type) => type.key === key) ||
        this.TAB_TYPES.BASIC
      );
    },
  },
  onReady() {
    // #ifdef APP-NVUE
    /* 可用窗口高度 - 搜索框高 - 状态栏高 */
    this.listHight =
      uni.getSystemInfoSync().windowHeight -
      uni.getSystemInfoSync().statusBarHeight -
      50 +
      "px";
    // #endif
    // #ifndef APP-NVUE
    this.listHight = "auto";
    // #endif
    // cdbRef = this.$refs.udb

    // 监听登录事件，然后确定好页面的重定向。
    uni.$on("uni-id-pages-login-success", function (data) {
      const url = appStore.redirectUrl;

      // console.log("uni-id-pages-login-success url: ", url)

      if (url) {
        uni.navigateTo({
          url,
          complete: () => {
            mutations.resetRedirectUrl();
          },
        });
      }
    });
  },
};
</script>
<style>
page {
  height: 100%;
}

/* #ifdef H5 */
uni-page-head {
  background-color: transparent !important;
}

uni-page-head .uni-page-head__title {
  color: #333333 !important;
}

/* #endif */
.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.content {
  flex: 1;
  overflow: auto;
  transition: background-color 0.3s ease;
}

.content.basic {
  background-color: rgba(76, 175, 80, 0.08);
}

.content.premium {
  background-color: rgba(218, 165, 32, 0.08);
}

.header {
  position: relative;
  width: 702rpx;
  height: 400rpx;
  flex-shrink: 0;
  margin: 100rpx auto 24rpx;
  /* 修改此处，增加顶部外边距 */
  transition: background-color 0.3s ease;
}

.sticky-tabs {
  position: sticky;
  top: 50rpx;
  z-index: 100;
  transition: all 0.3s ease;
}

.sticky-bg {
  background-color: rgba(255, 255, 255, 0.8);
}

.tabs {
  display: flex;
  flex-direction: row;
  justify-content: space-between; /* 修改为space-between */
  padding: 20rpx;
  transition: all 0.3s ease;
  background-color: transparent;
  border-bottom: 1px solid #eeeeee;
  flex-shrink: 0;
  height: 50rpx;
}

.filter-btn {
  display: flex;
  align-items: center;
  margin-left: auto; /* 添加这行让按钮靠右 */
  padding: 0 20rpx;
}

.tab {
  position: relative;
  padding: 0 30rpx;
  font-size: 14px;
  text-align: center;
  transition: all 0.3s ease;
  margin: 0 10rpx;
}

.tab.active {
  font-weight: 600;
  font-size: 15px;
}

.banner {
  width: 100%;
  height: 100%;
  overflow: hidden;
  border-radius: 16rpx;
}

.banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.list {
  padding: 24rpx;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.list-item {
  display: flex;
  flex-direction: column;
  background: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.item-image {
  width: 702rpx;
  height: 200rpx;
}

.tab-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
}

.tab-text {
  font-size: 10px;
  color: #666666;
}

.active .tab-text {
  color: #1976d2;
}

.loading {
  text-align: center;
  padding: 20rpx 0;
}

.loading text {
  color: #999;
  font-size: 28rpx;
}

.article-title {
  padding: 10rpx 20rpx;
  font-size: 28rpx;
  color: #333;
}
</style>
